Telegram Group & Telegram Channel
🧠 Уровень Pro: Медиана, ранги и NULL в Oracle SQL

📋 Есть таблица sales:


CREATE TABLE sales (
salesman_id NUMBER,
region VARCHAR2(50),
amount NUMBER
);


📦 Данные:

| salesman_id | region | amount |
|-------------|------------|--------|
| 101 | 'North' | 200 |
| 101 | 'North' | NULL |
| 102 | 'North' | 150 |
| 103 | 'North' | NULL |
| 104 | 'South' | 300 |
| 105 | 'South' | NULL |
| 106 | 'South' | 50 |
| 107 | 'South' | NULL |


🎯 Задача 2.0:
Вывести salesman_id, чья сумма продаж меньше медианы по региону,
и показать ранг продавца внутри региона по сумме продаж, где NULL = 0.

Подвохи:
- MEDIAN() доступен только в Oracle.
- Нужно предварительно агрегировать суммы.
- Продавцы с только NULL-продажами = 0.
- Ранг должен учитывать правильную сортировку и связи с регионом.

Решение:

```sql
WITH sales_total AS (
SELECT
salesman_id,
region,
NVL(SUM(amount), 0) AS total_sales
FROM sales
GROUP BY salesman_id, region
),
region_median AS (
SELECT
region,
MEDIAN(total_sales) AS region_median
FROM sales_total
GROUP BY region
),
ranked AS (
SELECT
st.salesman_id,
st.region,
st.total_sales,
r.region_median,
RANK() OVER (PARTITION BY st.region ORDER BY st.total_sales DESC) AS sales_rank
FROM sales_total st
JOIN region_median r ON st.region = r.region
)
SELECT *
FROM ranked
WHERE total_sales < region_median;
```

🧠 Объяснение:

1. `sales_total`: агрегируем продажи по продавцу, `NULL → 0`
2. `region_median`: считаем **медиану** продаж по каждому региону
3. `ranked`: добавляем `RANK()` по убыванию продаж внутри региона
4. Финальный фильтр: продажи ниже медианы

🔍 Пример вывода:

| salesman_id | region | total_sales | region_median | sales_rank |
|-------------|--------|-------------|----------------|-------------|
| 105 | South | 0 | 50 | 3 |
| 107 | South | 0 | 50 | 3 |
| 103 | North | 0 | 150 | 3 |

📌 Польза:

Отлично проверяет:
- знание оконных функций
- работу с медианой
- поведение `NULL` в агрегатах
- построение CTE-цепочек и аналитики

🔁 Можно расширить:
- Добавить ранги *по убыванию и по возрастанию*
- Вместо `MEDIAN()` использовать `PERCENTILE_CONT()`
- Построить дэшборд: кто всегда "ниже медианы" за месяц

@sqlhub



tg-me.com/sqlhub/1888
Create:
Last Update:

🧠 Уровень Pro: Медиана, ранги и NULL в Oracle SQL

📋 Есть таблица sales:


CREATE TABLE sales (
salesman_id NUMBER,
region VARCHAR2(50),
amount NUMBER
);


📦 Данные:

| salesman_id | region | amount |
|-------------|------------|--------|
| 101 | 'North' | 200 |
| 101 | 'North' | NULL |
| 102 | 'North' | 150 |
| 103 | 'North' | NULL |
| 104 | 'South' | 300 |
| 105 | 'South' | NULL |
| 106 | 'South' | 50 |
| 107 | 'South' | NULL |


🎯 Задача 2.0:
Вывести salesman_id, чья сумма продаж меньше медианы по региону,
и показать ранг продавца внутри региона по сумме продаж, где NULL = 0.

Подвохи:
- MEDIAN() доступен только в Oracle.
- Нужно предварительно агрегировать суммы.
- Продавцы с только NULL-продажами = 0.
- Ранг должен учитывать правильную сортировку и связи с регионом.

Решение:

```sql
WITH sales_total AS (
SELECT
salesman_id,
region,
NVL(SUM(amount), 0) AS total_sales
FROM sales
GROUP BY salesman_id, region
),
region_median AS (
SELECT
region,
MEDIAN(total_sales) AS region_median
FROM sales_total
GROUP BY region
),
ranked AS (
SELECT
st.salesman_id,
st.region,
st.total_sales,
r.region_median,
RANK() OVER (PARTITION BY st.region ORDER BY st.total_sales DESC) AS sales_rank
FROM sales_total st
JOIN region_median r ON st.region = r.region
)
SELECT *
FROM ranked
WHERE total_sales < region_median;
```

🧠 Объяснение:

1. `sales_total`: агрегируем продажи по продавцу, `NULL → 0`
2. `region_median`: считаем **медиану** продаж по каждому региону
3. `ranked`: добавляем `RANK()` по убыванию продаж внутри региона
4. Финальный фильтр: продажи ниже медианы

🔍 Пример вывода:

| salesman_id | region | total_sales | region_median | sales_rank |
|-------------|--------|-------------|----------------|-------------|
| 105 | South | 0 | 50 | 3 |
| 107 | South | 0 | 50 | 3 |
| 103 | North | 0 | 150 | 3 |

📌 Польза:

Отлично проверяет:
- знание оконных функций
- работу с медианой
- поведение `NULL` в агрегатах
- построение CTE-цепочек и аналитики

🔁 Можно расширить:
- Добавить ранги *по убыванию и по возрастанию*
- Вместо `MEDIAN()` использовать `PERCENTILE_CONT()`
- Построить дэшборд: кто всегда "ниже медианы" за месяц

@sqlhub

BY Data Science. SQL hub


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/sqlhub/1888

View MORE
Open in Telegram


Data Science SQL hub Telegram | DID YOU KNOW?

Date: |

Export WhatsApp stickers to Telegram on iPhone

You can’t. What you can do, though, is use WhatsApp’s and Telegram’s web platforms to transfer stickers. It’s easy, but might take a while.Open WhatsApp in your browser, find a sticker you like in a chat, and right-click on it to save it as an image. The file won’t be a picture, though—it’s a webpage and will have a .webp extension. Don’t be scared, this is the way. Repeat this step to save as many stickers as you want.Then, open Telegram in your browser and go into your Saved messages chat. Just as you’d share a file with a friend, click the Share file button on the bottom left of the chat window (it looks like a dog-eared paper), and select the .webp files you downloaded. Click Open and you’ll see your stickers in your Saved messages chat. This is now your sticker depository. To use them, forward them as you would a message from one chat to the other: by clicking or long-pressing on the sticker, and then choosing Forward.

The global forecast for the Asian markets is murky following recent volatility, with crude oil prices providing support in what has been an otherwise tough month. The European markets were down and the U.S. bourses were mixed and flat and the Asian markets figure to split the difference.The TSE finished modestly lower on Friday following losses from the financial shares and property stocks.For the day, the index sank 15.09 points or 0.49 percent to finish at 3,061.35 after trading between 3,057.84 and 3,089.78. Volume was 1.39 billion shares worth 1.30 billion Singapore dollars. There were 285 decliners and 184 gainers.

Data Science SQL hub from sg


Telegram Data Science. SQL hub
FROM USA